<template>

    <div class="innerContainer">
        <common-title text="项目编辑">
            <template #expand>
                <el-button type="primary" plain size="mini" @click="router.go(-1)">返回上一级</el-button>
            </template>
        </common-title>
        <div class="innerPane">
            <div class="innerTop">
                <el-row>
                    <el-col :span="11">
                        <el-input v-model="projectFilterText" placeholder="" />
                        <div class="tree-wrapper">
                            <el-tree ref="projectTreeRef" class="filter-tree" :data="projectData" :props="proTreeProps"
                                default-expand-all highlight-current="true" node-key="id"
                                :filter-node-method="filterProjectNode" @node-click="handleProjectClick"
                                :render-content="renderContent">
                            </el-tree>
                        </div>
                    </el-col>
                    <el-col :span="2"> </el-col>
                    <el-col :span="11">
                        <el-input v-model="equipmentFilterText" placeholder="" />

                        <div class="tree-wrapper">

                            <el-tree ref="equipmentTreeRef" highlight-current="true" class="filter-tree" show-checkbox
                                node-key="code" :data="equipmentData" :props="equipTreeProps" default-expand-all
                                :check-strictly="true" :filter-node-method="filterEquipmentNode"
                                @check="handleEquipmentCheck" />
                        </div>
                    </el-col>
                </el-row>

            </div>

            <div class="innerBottom">
                <div class="filterArea">
                    <el-form :inline="true" :model="filterForm" class="demo-form-inline">
                        <el-form-item label="设备名称">
                            <el-input @keyup.enter="onSearch" v-model="searchForm.name"
                                placeholder="请输入设备名称"></el-input>
                        </el-form-item>
                        <el-form-item label="设备编码">
                            <el-input @keyup.enter="onSearch" v-model="searchForm.code"
                                placeholder="请输入设备编码"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-button plain type="primary" @click="onSearch">查询</el-button>
                            <el-button plain @click="onClear">重置</el-button>
                        </el-form-item>
                    </el-form>
                </div>

               <el-table :data="tableData" border row-key="id" style="width: 100%;overflow-y: auto;" 
                        :cell-style="{ textAlign: 'center' }" row-class-name="fixed-row" @row-click="handleRowClick">
                        <el-table-column type="index" label="序号" width="50" :index="indexMethod" />
                        <el-table-column header-align="center" prop="mapName" label="设备名" width="180" />
                        <el-table-column header-align="center" prop="modelCode" label="产品类型" width="180" />
                        <el-table-column header-align="center" prop="mapSnCode" label="sn码" width="160" />
                        <el-table-column header-align="center" prop="projectName" label="所属项目" />

                        <el-table-column header-align="center" prop="gpsstatus" label="GPS同步" width="120">
                            <template #default="scope">
                                {{ getGpsText(scope.row) }}
                            </template> </el-table-column>
                        <el-table-column header-align="center" prop="lastRcvTime" label="近期通信" />

                        <el-table-column label="操作" header-align="center" width="120" prop="col9">
                            <template #default="scope">
                                <el-link type="primary" size="small" @click="view(scope.$index, scope.row)">详情</el-link>

                                <el-link type="primary" size="small" @click="edit(scope.$index, scope.row)">设置</el-link>
                            </template>
                        </el-table-column>
                    </el-table>
                    <!-- 分页 -->
                    <el-pagination class="pagination" :current-page="searchForm.current" :page-size="searchForm.size"
                        :page-sizes="[10, 20, 30, 40, 100]" layout="->,total, sizes, prev, pager, next, jumper"
                        :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>

        </div>

        <project-view ref="projectViewRef" @confirm="initProTree" />

        <group-view ref="groupViewRef" @confirm="initProTree" />

        <point-view ref="pointViewRef" @confirm="initProTree" />
    </div>

</template>

<script setup>
import CommonTitle from "@/components/CommonTitle.vue";

import { onMounted, ref, reactive, watch, nextTick } from "vue";
import { ElMessage, ElTree, ElButton, ElMessageBox, ElText } from "element-plus";

import { useRouter } from "vue-router";

import {
    equipmentList, projectTree, equipmenetTree, projectSave
} from "@/utils/requests";


import ProjectView from "./projectView.vue";
import GroupView from "./groupView.vue";
import PointView from "./pointView.vue";

onMounted(() => {
    searchForm.projectId = router.currentRoute.value.query.projectId;
    onSearch();
    initProTree();
    initEquipTree();
});


const projectFilterText = ref('')
const projectTreeRef = ref();

const equipmentFilterText = ref('')
const equipmentTreeRef = ref();


watch(projectFilterText, (val) => {
    projectTreeRef.value?.filter(val)
})
watch(equipmentFilterText, (val) => {
    equipmentTreeRef.value?.filter(val)
})


const projectViewRef = ref(null);
const groupViewRef = ref(null);
const pointViewRef = ref(null);


const treeBtnCoifgs = [
    {
        level: 1, addBtn: true, delBtn: false, addText: '添加测组', delText: '删除',
        handlerEidt: (node, data) => projectViewRef.value.openDialog(node, data),
        handlerAdd: (node, data) => { groupViewRef.value.openDialog(node, data) }
    },
    {
        level: 2, addBtn: true, delBtn: true, addText: '添加测点', delText: '删除',
        handlerEidt: (node, data) => groupViewRef.value.openDialog(node, data),
        handlerAdd: (node, data) => pointViewRef.value.openDialog(node, data),
        handlerDel: (node, data) => { }
    },
    {
        level: 3, addBtn: false, delBtn: true, addText: '', delText: '删除',
        handlerEidt: (node, data) => pointViewRef.value.openDialog(node, data),
        handlerDel: (node, data) => { }
    },
]

const renderContent = (h, { node, data }) => {

    let btnConfg = treeBtnCoifgs.find(item => item.level === data.projectLevel);


    return h('div', { class: 'custom-tree-node' }, [
        h('span', null, node.label),

        h('div', { style: 'margin-left:auto;' }, [

            btnConfg.level == 3 && data.ext?.adName ? h(ElText, {
                class: 'mx-1',
                style: 'margin-right:10px',
                type: 'info'
            }, data.ext?.adName) : null,


            h(ElButton, {
                type: 'primary',
                link: true,
                style: 'margin-left:4px',
                onClick: (e) => {
                    e.stopPropagation()
                    btnConfg.handlerEidt(node, data);
                }
            }, "编辑"),

            //删除
            btnConfg.delBtn ? h(ElButton, {
                type: 'danger',
                link: true,
                style: 'margin-left:4px',
                onClick: (e) => {
                    e.stopPropagation()
                    remove(node, data)
                }
            }, btnConfg.delText) : null,

            //添加 下级节点
            btnConfg.addBtn ? h(ElButton, {
                type: 'warning',
                link: true,
                onClick: (e) => {
                    e.stopPropagation()
                    btnConfg.handlerAdd(node, data);
                }
            }, btnConfg.addText) : null
        ])
    ])
}

const handleProjectClick = (data) => {
    if (data.ext?.adId) {
        equipmentTreeRef.value.setCheckedKeys([data.ext.adId]);

        const nodeEl = document.querySelector(`[data-key="${data.ext.adId}"]`); // 2

        nodeEl?.scrollIntoView({ behavior: 'smooth', block: 'center' }); // 3

    } else {
        equipmentTreeRef.value.setCheckedKeys([]);
    }

}

/**
 *  设备节点多选框选中事件
 * @param data  当前节点的数据
 * @param checked   是否被选中（布尔值）
 * @param indeterminate 是否为半选状态（布尔值）
 */
const handleEquipmentCheck = (checkedNode, { checkedKeys, halfCheckedKeys }) => {

    if (checkedNode.level === 1) {
        ElMessage.warning({
            message: "只能选择通道节点", duration: 2000
        });

        equipmentTreeRef.value.setChecked(checkedNode.code, false, false)

        return;
    }

    let projectNode = projectTreeRef.value.getCurrentNode();

    if (!projectNode || projectNode.projectLevel !== 3) {
        ElMessage.warning({
            message: "请先选择需要绑定通道的测点", duration: 2000
        });

        equipmentTreeRef.value.setChecked(checkedNode.code, false, false);

        return;
    }

    let isChecked = checkedKeys.includes(checkedNode.code);

    let confirmInfo = `确认 ${isChecked ? "绑定" : " 取消绑定"} 测点【${projectNode.projectName}】与通道【${checkedNode.name}】吗？`;


    ElMessageBox.confirm(confirmInfo, "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
    })
        .then(() => {

            const fd = new FormData()
            fd.append('id', projectNode.id)

            let relJson = {};

            if (isChecked) {
                relJson.adId = checkedNode.code;
            }

            if (projectNode.ext?.attachId) {
                relJson.attachId = projectNode.ext.attachId;
            }
            if (projectNode.ext?.leftTop) {
                relJson.leftTop = projectNode.ext.leftTop;
            }

            fd.append('relJson', JSON.stringify(relJson));

            projectSave(fd).then((data) => {
                if (data) {
                    equipmentTreeRef.value.setCheckedKeys([], true);

                    equipmentTreeRef.value.setChecked(checkedNode.code, isChecked, false);

                    initProTree();

                    ElMessage.success("保存成功");

                } else {
                    ElMessage.error("保存失败");
                }
            });
        })
        .catch(() => {
            //
            equipmentTreeRef.value.setChecked(checkedNode.code, !isChecked, false);
        });
}

const handleRowClick = (row, column, event) => {
    equipmentFilterText.value = row.name;
}

const proTreeProps = {
    children: 'children',
    label: 'projectName',
    level: 'projectLevel',
    id: 'id'
}

const filterProjectNode = (value, data) => {
    if (!value) return true
    return data.projectName.includes(value) || (data.parentName?.includes(value));
}


const filterEquipmentNode = (value, data) => {
    if (!value) return true;
    return data.name.includes(value) || (data.parentName?.includes(value));
}


let projectData = ref([
])

const initProTree = () => {
    projectTree({ parentId: searchForm.projectId }).then((res) => {
        projectData.value = res;
    })
}

const equipTreeProps = {
    children: 'children',
    label: 'name',
    level: 'level',
    id: 'code'
}

let equipmentData = ref([
])

const initEquipTree = () => {
    equipmenetTree({ projectId: searchForm.projectId }).then((res) => {
        equipmentData.value = res;
    })
}


let tableData = ref([]);

let total = ref(0);

const router = useRouter();
// 搜索条件
const searchForm = reactive({
    current: 1,
    size: 10,
    name: null,
    code: null,
    projectId: null,
});



// 累加序号方法
const indexMethod = (index) => {
    return (searchForm.current - 1) * searchForm.size + index + 1;
};
const handleSizeChange = (size) => {
    searchForm.size = size;
    searchForm.current = 1;
    onSearch();
};
const handleCurrentChange = (current) => {
    searchForm.current = current;
    onSearch();
};

const onSearch = () => {
    equipmentList(searchForm).then((res) => {
        tableData.value = res.records;
        total.value = res.total;
    });
};
const onClear = () => {
    searchForm.name = "";
    searchForm.code = "";
    searchForm.size = 10;
    searchForm.current = 1;
    search();
};

const getGpsText = (rowData) => {
    return rowData.gpsstatus === 1 ? "是" : "否";
};

</script>

<style scoped lang="scss">
/* 顶部：固定高 */
.innerTop {
    height: 350px;
    /* 想改高度直接改这里 */
    // color: #fff;
    align-items: center;
    padding: 0 16px;
}

.innerTop .el-row {
    height: 100%;
}

.tree-wrapper {
    height: 300px;
    overflow-y: auto;
}

/* 中间：自动占满剩余 */
.innerBottom {
    margin-top: 20px;
    max-height: calc(100% - 350px - 20px);
     overflow-y: auto;
    flex: 1;
    /* 关键：剩余空间全部给它 */
    // overflow: auto;
    /* 内容过高时出滚动条 */
    background: #f5f7fa;
    padding: 10px;
}
 
/* 你自己的节点盒子：左右分列 */
::v-deep(.custom-tree-node) {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
}
</style>